var authName = '', userCity = '', userCategory = '';

$(".include").each(function () {
    if (!!$(this).attr("file")) {
        var $includeObj = $(this);
        $(this).load($(this).attr("file"), function (html) {
            $includeObj.after(html).remove();
        })
    }
});

function initEvent() {
    $(window).bind("load resize", function() {
        var topOffset = 50;
        width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
        if (width < 768) {
            $('div.navbar-collapse').addClass('collapse')
            topOffset = 100; // 2-row-menu
        } else {
            $('div.navbar-collapse').removeClass('collapse')
        }

        var height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height;
        height = height - topOffset;
        if (height < 1) height = 1;
        if (height > topOffset) {
            $("#page-wrapper").css("min-height", (height) + "px");
        }
    })
}

function hashchangehandler() {
    var hash = window.location.hash || '#pages/home.html';
    hash = hash.replace("#", "");
    divLoadPage(hash);
    scroll(0, 0);
    hash = hash.replace("pages/", "");
    hash = hash.replace(".html", "");
    $('.nav a').removeClass('active');
    $("#" + hash).addClass('active');
}

function onMenuClick(url) {
    location.hash = url;
    if (!+'\v1' && !'1' [0]) {
        hashchangehandler();
    }
}

function divLoadPage(url) {
    $.get(url, function(result) {
        $("#page-wrapper").html(result);
    });
}


function initPara() {
    Messenger.options = {
        extraClasses: 'messenger-fixed messenger-on-bottom',
        theme: 'flat'
    };
    Handlebars.registerHelper("math", function(lvalue, operator, rvalue,
        options) {
        lvalue = parseFloat(lvalue);
        rvalue = parseFloat(rvalue);
        return {
            "+": lvalue + rvalue,
            "-": lvalue - rvalue,
            "*": lvalue * rvalue,
            "/": lvalue / rvalue,
            "%": lvalue % rvalue,
            "idx": (lvalue + 1) + ((currentPageNo - 1) * pageRows)
        }[operator];
    });
}


function zhget(url, data, callback) {
    zhajax(url, data, 'GET', callback);
}

function zhpost(url, data, callback) {
    zhajax(url, data, 'POST', callback);
}

function zhput(url, data, callback) {
    zhajax(url, data, 'PUT', callback);
}

function zhdelete(url, data, callback) {
    zhajax(url, data, 'DELETE', callback);
}

function zhajax(url, data, type, callback) {
    $.ajax({
        url:  url,
        data: data,
        type: type,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Session-Id", getCookie('sid'));
        },
        success: function(result, textStatus, jqXHR) {
            var sid = jqXHR.getResponseHeader("Session-Id");
            if(sid != null && sid.length > 5)
                setCookie('sid', sid, 1);
            if (callback) {
                callback(result);
            }
        }
    });
}


function ajaxSynGet(url, callback) {   //同步GET请求
    $.ajax({
        url:  url,
        data: {},
        async: false,
        type: 'GET',
        success: function(result, textStatus, jqXHR) {
            if (callback) {
                callback(result);
            }
        }
    });
}

function ajaxInitSession(url, callback) {   //专用于session初始调用
    $.ajax({
        url:  url,
        data: {},
        type: 'POST',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Session-Id", getCookie('sid'));
            xhr.setRequestHeader("Session-Init", "SessionInit");        //具有此参数，服务端才会新建session id
        },
        success: function(result, textStatus, jqXHR) {
            var sid = jqXHR.getResponseHeader("Session-Id");            //只存有效的session id，否则会冲掉有效值。
            setCookie('sid', sid, 1);
            if (callback) {
                callback(result);
            }
        }
    });
}

function upajax(url,data,callback) {
    $.ajax({
        url:  url,
        data: data,
        type: 'POST',
        processData : false,        //必须false才会避开jQuery对 formdata 的默认处理;XMLHttpRequest会对 formdata 进行正确的处理
        contentType : false,        //必须false才会自动加上正确的Content-Type
        success: function(result, textStatus, jqXHR) {
            if (callback) {
                callback(result);
            }
        }
    });
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            var c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString())
}

String.prototype.GetValue = function (parm) {
    var reg = new RegExp("(^|&)" + parm + "=([^&]*)(&|$)");
    var r = this.substr(this.indexOf("\?") + 1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function showSuccess(message) {
    Messenger().post({
        message: message,
        type: 'success',
        showCloseButton: true
    });
}

function showError(message) {
    Messenger().post({
        message: message,
        type: 'error',
        showCloseButton: true
    });
}

function buildPlainTable(datas, template, placeholder) {
    var temp = Handlebars.compile($("#" + template).html());
    $("#" + placeholder).html(temp({
        datas: datas
    }));
}

function buildTable(datas, template, placeholder) {
    var temp = Handlebars.compile($("#" + template).html());
    $("#" + placeholder).html(temp({
        datas: datas.rows
    }));
    buildPaginator('paginator', datas.count);
}

function buildPaginator(paginator, total) {
    var options = {
        currentPage: currentPageNo,
        totalPages: total,
        bootstrapMajorVersion: 3,
        onPageClicked: function(e, originalEvent, type, page) {
            currentPageNo = page;
            if(9 == userCategory ){
                queryListAll();
            }else{
                queryList();
            }
        }
    };
    $('#' + paginator).bootstrapPaginator(options);
}

function templateRender(data, id) {
    var temp = Handlebars.compile($("#" + id).html());
    $("#" + id).html(temp(data));
}

function loginout(){
    zhpost('/op/loginout', {
    }, function (result) {
        var rs = JSON.parse(result);
        if (!rs.outcome) {
            alert(rs.error);
            $('#username').focus();
        }
        else {
            //alert("你已经成功登陆，将跳转到商家后台。");
            window.location=rs.target;
        }
    });
}

////////////////////////////////////////////////////////////////////////////////////////////////////////

var AUTHS = ['admin'];   //shang

function initSession () {
    ajaxInitSession("/op/authorization", function (result) {
        var rs = JSON.parse(result);
        if(rs.username.length > 2 && rs.usercategory > 7){
            setCookie('username', rs.username, 1);
            setCookie('usercategory', rs.usercategory, 1);
            setCookie('usercity', rs.usercity, 1);
        }
        else{                                    //没有特殊权限，不允许访问
            var curUrl = location.href;
            for(var al in AUTHS){
                if(curUrl.indexOf(AUTHS[al])>-1){
                    alert("你没有访问些页面的权限！");
                    window.location = "index.html";
                }
            }
        }

        //不需要特殊权限的session处理在这里进行
        window.document.getElementsByTagName('body')[0].style.display = "block";

        $('#side-menu'+rs.usercategory).css("display" , "block");
        $('#side-menu'+rs.usercategory).metisMenu();

        initEvent();
        initPara();
        $(window).bind('hashchange', hashchangehandler);
        hashchangehandler();
    });
}
